﻿using System;
using UnityEngine;

namespace ZWFrameWork
{
    public abstract class SingletonMonoBehaviour<T>:MonoBehaviour where T : SingletonMonoBehaviour<T>
    {
        protected static T instance;
        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = (T)FindObjectOfType(typeof(T));
                    if (instance == null)
                    {
                        GameObject go = GameObject.Find(typeof(T).Name);
                        if (go == null)
                        {
                            go = new GameObject(typeof(T).Name);

                        }
                        
                        DontDestroyOnLoad(go);
                        instance = go.AddComponent<T>();
                    }

                    if (instance == null)
                    {
                        GameUtilty.Error("An instance of {0} is needed in the scene, but there is none.",typeof(T));
                    }
                }
                return instance;
            }
        }

        /// <summary>
        /// 销毁的时候处理数据
        /// </summary>
        private void OnDestroy()
        {
            if (instance != null)
            {
                instance.ClearData();
            }
        }

        public abstract void ClearData();
        
    }
}